package com.hsmpay.yl8583.service;

import com.hsmpay.base.PayBaseService;
import com.hsmpay.qian4.pojo.BalanceResult;
import com.hsmpay.qian4.pojo.PurchaseResult;
import com.hsmpay.qian4.pojo.RevocationResult;
import com.hsmpay.qian4.pojo.send.ICCardParam;
import com.hsmpay.qian4.pojo.send.SendParam;
import com.hsmpay.utils.StringBUtils;
import com.hsmpay.utils.WriteFile;
import com.hsmpay.utils.YLCode;
import com.hsmpay.utils.system.ConConfig;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import java.util.Map;


/**
 * Created by zhy on 15/11/10.
 */
public class HanXinService extends PayBaseService{
    public static String debug = ConConfig.getAttribute("HANXIN_DAISHOU_DEBUG_STATUS");
    static Logger log = Logger.getLogger(HanXinService.class);
    public HanXinToBoss st = null;
    public String merchantId = "";
    public String terminalId = "";
    public String batch = "";
    static WriteFile wf = new WriteFile("ds_HanXin");

    /**
     * 大pos
     * @param merchantId 商户号
     * @param terminalId 终端号
     * @param batch 批次号
     * @param muKey 解密秘钥
     * @param MasterKey 主密钥（密文）
     * @param PinKey
     * @param MacKey  单des  使用对称3des
     */
    public HanXinService(String merchantId, String terminalId, String batch, String MasterKey, String PinKey, String MacKey, String trkKey, String sensKey, Map<String, String> hanXinConfig){
        this.merchantId = merchantId;
        this.terminalId = terminalId;
        this.batch = batch;
        st = new HanXinToBoss(merchantId,terminalId,batch,MasterKey,PinKey,MacKey,trkKey, sensKey, hanXinConfig);
    }
    /**
     * 55域
     * @param iccParam
     * @return
     */
    private String getIcc55(ICCardParam iccParam){
        if(null == iccParam || StringUtils.isEmpty(iccParam.getIcCardYu())) return "";
        String bit55Str = iccParam.getBit55();
        log.debug("IC卡 bit55："+bit55Str);
        return bit55Str;
    }

    /**
     * 有效期 返回4位  5F24的值前4个字符  有效期  5F24是：YYMMDD
     * @param iccParam
     * @return
     */
    private static String getIcc14(ICCardParam iccParam){
        if(null == iccParam || StringUtils.isEmpty(iccParam.getP_5f24())) return "";
        String r = iccParam.getP_5f24().substring(0, 4);
        return r;
    }

    /**
     * IC卡序列 5F34的值,5F34的值不足3位前补0 多于3位进行处理
     * @param iccParam
     * @return
     */
    private String getIcc23(ICCardParam iccParam){
        if(null == iccParam || StringUtils.isEmpty(iccParam.getP_5f34())) return "";
        String r = iccParam.getP_5f34();
        if(r.length() <= 3){
            r = StringBUtils.supplyAll(r, 3);
        }else if (r.length() > 3 && r.contains("1")){
            r = "001";
        }else{
            r = "000";
        }
        return r;
    }

    /**
     * 查询余额
     * @param send
     * @throws Exception
     * return reqCode reqMsg balance 单位是元
     */
    public BalanceResult balanceEnquiry(SendParam send)throws Exception{
        BalanceResult br = new BalanceResult();
        br.setAccountNumber(send.getAccountNumber());//卡号
        br.setBalanceCurrency("RMB");//币种
        String resStr = "";
        if(!isFormal()){
            log.debug("测试环境");
            resStr = "0_00_储蓄帐户 ￥259959.17";
        }else{
            send.setTrack3Data("");//####屏蔽3磁道
            String bit14 = getIcc14(send.getIccParam());
            String bit23 = getIcc23(send.getIccParam());
            String bit55 = getIcc55(send.getIccParam());
            resStr = st.Query(send.getTrack2Data(), send.getTrack3Data(), send.getPin(),send.getAccountNumber(),send.getBankOrderNum(),bit23,bit55,bit14);
        }
        log.debug("翰鑫查询余额响应："+resStr);
        String[] resArray = resStr.split("_");
        if("-1".equals(resArray[0])){
            br.setReqCode("9999");
            br.setReqMsg("由于网络原因，银联接口异常，请稍候再试！");
        }else{
            String reqCode =  StringBUtils.supplyAll(resArray[1], 4);
            br.setReqCode(reqCode);
            if("0000".equals(reqCode)){
                br.setReqMsg("查询余额成功！");
                String money = resArray[2].split("￥")[1];//单位是元
                Long balance = (long)(Double.parseDouble(money) * 100);//乘以100 变成分
                br.setBalance(balance.toString());
            }else{
                br.setReqMsg(null == YLCode.getMsg(resArray[1]) ? "查询余额失败！" : YLCode.getMsg(resArray[1]));
            }
        }
        return br;
    }

    /**
     * 收款
     * @param send
     * @return
     * @throws Exception
     */
    public PurchaseResult billPayment(SendParam send)throws Exception{
        PurchaseResult rs = new PurchaseResult();
        String money = StringBUtils.supplyAll(send.getTransAmt(), 12);
        String resStr = "";
        if(!isFormal()){
            log.debug("测试环境");
            resStr = "0_6226220112722482_000000000001_100011_150602_0807_ _000002350153_151878_00";
        }else{
            send.setTrack3Data("");//####屏蔽3磁道
            String bit14 = getIcc14(send.getIccParam());
            String bit23 = getIcc23(send.getIccParam());
            String bit55 = getIcc55(send.getIccParam());
            resStr = st.BillPayment(send.getTrack2Data(), send.getTrack3Data(), send.getPin(), money, send.getAccountNumber(), send.getBankOrderNum(), bit23, bit55, bit14);
        }
        log.debug("翰鑫消费响应："+resStr);
        String[] resArray = resStr.split("_");
        if("-1".equals(resArray[0])){//
            rs.setStatus(0);//
            rs.setReqCode("9999");
            rs.setReqMsg("由于网络原因，银联接口异常，请稍候再试！");
        }else{
            rs.setStatus(1);//
            String reqCode =  StringBUtils.supplyAll(resArray[resArray.length - 1], 4);
            rs.setReqCode(reqCode);
            rs.setAccountNumber(resArray[1]);
            rs.setBatchId(send.getBatchId());//批次号
            //rs.setAccountNumber(resArray[2]);//金额
            rs.setBankOrderNum(resArray[3]);//流水号
            rs.setBankTransTime(resArray[4]);//交易时间
            rs.setBankTransDate(resArray[5]);//交易日期
            rs.setExpireDate(resArray[6]);//有效期
            rs.setBankRef(resArray[7]);//参考号 37
            rs.setAuthorizationCode(resArray[8]);//授权号 38
            if("0000".equals(reqCode)){
                rs.setReqMsg("收款成功");
            }else{
                log.debug("------------"+resArray[1]+"------------");
                rs.setReqMsg( null == YLCode.getMsg(resArray[resArray.length - 1]) ? "交易失败！" : "交易失败-"+ YLCode.getMsg(resArray[resArray.length - 1]));
            }
        }
        return rs;
    }

    /**
     * 冲正接口
     * @param send
     * @return
     * @throws Exception
     */
    public RevocationResult unBillPayment(SendParam send)throws Exception{
        RevocationResult rr = new RevocationResult();
        String money = StringBUtils.supplyAll(send.getTransAmt(), 12);
        String authorizationCode = send.getAuthorizationCode();
        String bankRef = send.getBankRef();
        if(null == authorizationCode) authorizationCode = "";
        if(null == bankRef) bankRef = "";

        String resStr = "";
        if(!isFormal()){
            log.debug("测试环境");
            resStr = "0_ _000000000001_100011_ _ _ _000002350153_151878_00_ _ ";
        }else{
            send.setTrack3Data("");//####屏蔽3磁道
            String bit14 = getIcc14(send.getIccParam());
            String bit23 = getIcc23(send.getIccParam());
            String bit55 = getIcc55(send.getIccParam());
            String track3Data = null == send.getTrack3Data() ? "" : send.getTrack3Data();

            resStr = st.unBillPayment(send.getPin(), send.getTrack2Data(), track3Data, money, send.getAccountNumber(), send.getBankOrderNum(), authorizationCode,bit23,bit55,bit14,send.getResponseCode())+" ";//此处需要39域信息
        }
        log.debug("翰鑫冲正接口响应："+resStr);
        String[] resArray = resStr.split("_");

        if("-1".equals(resArray[0])){//
            rr.setStatus(0);//
            rr.setReqCode("9999");
            rr.setReqMsg("由于网络原因，银联接口异常，请稍候再试！");
        }else{
            rr.setStatus(1);//
            String reqCode =  StringBUtils.supplyAll(resArray[resArray.length - 3], 4);
            rr.setReqCode(reqCode);
            //resArray[1] 主帐号 resArray[2]  金额  resArray[3] 流水号  resArray[4] 交易时间  resArray[5] 交易日期  resArray[6] 失效日期  resArray[7] 参考号  resArray[8] 授权号
            rr.setAccountNumber(resArray[1]);
            rr.setBankOrderNum(resArray[3]);
            rr.setBankTransTime(resArray[4]);
            rr.setBankTransDate(resArray[5]);
            rr.setExpireDate(resArray[6]);
            rr.setBankRef(resArray[7]);
            rr.setAuthorizationCode(resArray[8]);
            if("0000".equals(reqCode)){
                rr.setReqMsg("冲正成功");
            }else{
                rr.setReqMsg( null == YLCode.getMsg(resArray[resArray.length - 3]) ? "冲正失败！" : "冲正失败-"+ YLCode.getMsg(resArray[resArray.length - 3]));
            }
        }
        return rr;
    }
}
